import { defineComponent, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElButton,
  ElForm,
  ElFormItem,
  ElInputNumber,
  ElMessage,
  ElSelect,
  ElOption,
  ElCol,
  ElRow,
  ElIcon
} from 'element-plus'

import type { FormInstance, FormRules } from 'element-plus'
import type { bindingLampType, lampMesListType, lampType, postLampType } from './typings'
import { GUTTER } from '~/utils/const'
import { CirclePlus, CircleClose } from '@element-plus/icons-vue'

export default defineComponent({
  setup(props, { expose }) {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>()
    const ruleForm = reactive<bindingLampType>({
      nodeList: [{}]
    })

    const rules = reactive<FormRules>({
      name: [{ required: true, message: '单灯不能为空', trigger: 'blur' }]
    })

    const state = reactive({
      lampList: [],
      visible: false,
      id: ''
    })

    const open = async (id: string) => {
      state.visible = true
      state.id = id
      // 获取灯杆绑定的单灯
      const res = await store.dispatch('singleLamp/GetSingleLampAndpost', { lampPostId: id })
      ruleForm.nodeList =
        res.data.length > 0
          ? res.data.map((item: postLampType) => {
              return {
                lampNodeId: item.lampNodeId,
                lampNum: item.lampNum
              }
            })
          : [{}]
      const newArr: any = []
      res.data.map((item: lampMesListType) =>
        newArr.push({
          id: item.lampNodeId,
          name: item.lampNodeName
        })
      )
      state.lampList = newArr
    }

    const cancel = () => {
      state.visible = false
    }
    // 新增调光参数
    const addLamp = () => {
      ruleForm.nodeList!.push({})
    }
    // 删除调光参数
    const delLamp = (index: number) => {
      ruleForm.nodeList!.splice(index, 1)
    }
    //  提交
    const submitForm = () => {
      ruleFormRef.value?.validate(async (valid) => {
        if (valid) {
          const params = { ...ruleForm }
          params.lampPostId = state.id
          params.nodeList.map((item) => (item.lampPostId = state.id))
          const { code } = await store.dispatch('singleLamp/LamppostBindLamp', params)
          if (code === 200) {
            ElMessage({
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            cancel()
          }
        }
      })
    }
    //  取消
    const resetForm = () => {
      ruleFormRef.value?.resetFields()
      cancel()
    }

    // 关键字搜索单灯
    const handleSearchLamp = async (value: string) => {
      if (value) {
        const res = await store.dispatch('singleLamp/GetsingleLampBykeyword', { keyword: value })
        state.lampList = res.data
      }
    }

    expose({ open })
    return () => (
      <ElDialog
        title="绑定单灯"
        modelValue={state.visible}
        beforeClose={cancel}
        closeOnClickModal={false} // 点遮罩层不关弹窗
        draggable // 可拖拽
        width={700}
        v-slots={{
          footer: () => (
            <>
              <ElButton onClick={resetForm}>取消</ElButton>
              <ElButton type="primary" onClick={submitForm}>
                确定
              </ElButton>
            </>
          )
        }}
      >
        <ElForm
          ref={ruleFormRef}
          model={ruleForm}
          rules={rules}
          label-width="120px"
          labelPosition="right"
        >
          <ElRow gutter={GUTTER}>
            <ElCol span={20}>
              <ElFormItem label="关联单灯">
                {ruleForm.nodeList?.map((item: lampMesListType, index) => (
                  <div style="display:flex">
                    <ElFormItem labelWidth={0}>
                      <ElInputNumber
                        v-model={item.lampNum}
                        placeholder="回路"
                        style="width:120px;margin:0 12px 10px 0"
                        min={1}
                      />
                    </ElFormItem>
                    <ElFormItem labelWidth={0}>
                      <ElSelect
                        v-model={item.lampNodeId}
                        placeholder="请选择单灯"
                        filterable
                        remote
                        remoteMethod={handleSearchLamp}
                        style="margin:0 12px 10px 0"
                      >
                        {state.lampList?.map((el: lampType) => (
                          <ElOption value={el?.id} key={el?.id} label={el?.name}></ElOption>
                        ))}
                      </ElSelect>
                    </ElFormItem>
                    {ruleForm.nodeList?.length < 6 && (
                      <div onClick={addLamp} style="margin:4px 12px 0 0">
                        <ElIcon size={20} color="red">
                          <CirclePlus />
                        </ElIcon>
                      </div>
                    )}
                    {ruleForm.nodeList?.length > 1 && (
                      <div onClick={() => delLamp(index)}>
                        <ElIcon size={20} style="margin-top:4px">
                          <CircleClose />
                        </ElIcon>
                      </div>
                    )}
                  </div>
                ))}
              </ElFormItem>
            </ElCol>
          </ElRow>
        </ElForm>
      </ElDialog>
    )
  }
})
